// pages/cashier_qr/cashier_qr.js
var intervalid;
var app = getApp();
Page({

  /**
	 * 页面的初始数据
	 */
  data: {
    qrcode: "",
    vedioSrc: "",
    adShow: false,
    hotel_id: '',
    storeBalance:false,
    store_id:''
  },

  /**
	 * 生命周期函数--监听页面加载
	 */
  onLoad: function(options) {
    this.setData({
      imgPath: app.globalData.imgPath
    })
    if(options.name == 'storeBalance'){
      // 门店独立余额
      this.setData({
        store_id:options.store_id,
        name:options.name,
        storeBalance:true
      });
      wx.setNavigationBarTitle({
        title: '我的二维码',
      });
      this.getBalanceCode();
      return;
    }
    if (app._isTextEmpty(options.hotel_id)) {
      this.getQrcode();
    } else {
      this.setData({
        hotel_id: options.hotel_id
      });
      this.getHotelData();
    }
  },

  /**
	 * 生命周期函数--监听页面初次渲染完成
	 */
  onReady: function() {},

  /**
	 * 生命周期函数--监听页面显示
	 */
  onShow: function() {

  },

  /**
	 * 生命周期函数--监听页面隐藏
	 */
  onHide: function() {

  },

  /**
	 * 生命周期函数--监听页面卸载
	 */
  onUnload: function() {
    this.closeTimeInterval();
  },

  /**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
  onPullDownRefresh: function() {

  },

  /**
	 * 页面上拉触底事件的处理函数
	 */
  onReachBottom: function() {

  },

  /**
	 * 用户点击右上角分享
	 */
  onShareAppMessage: function() {
    let store_id = this.options.store_id || this.data.store_id;
    return {
      path: "/packageC/o2o/HomeSeller/HomeSeller?store_id=" + store_id,
    };
  },
  // 门店独立余额
  getBalanceCode(){
    var that = this;
    let urlStr = app.getNetAddresss('plugin.store-cashier.frontend.store.balance.agent.getQrCode');
    app._getNetWork({
      url: urlStr,
      data:{
        store_id:this.data.store_id
      },
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            qrcode: res.data.qr_code,
            private_chain: res.data.private_chain,
            store_info: res.data.store_info,
            adShow: false
          });
        }
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },
  //获取收货地址
  getQrcode() {
    var that = this;
    let urlStr = app.getNetAddresss('plugin.store-cashier.frontend.cashier.QrCode');
    app._getNetWork({
      url: urlStr,
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            qrcode: res.data.small_url,
            adShow: res.data.audio_open == 1 ? true : false
          });
          if(!that.options.store_id){
            that.data.store_id= res.data.store_id
          }
          if (res.data.audio_open == 1) {
            that.openTime(res.data.store_id);
          }
        }
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },
  openTime(id) {
    intervalid = setInterval(() => {
      var that = this;
      let urlStr = app.getNetAddresss('plugin.store-cashier.frontend.cashier.voice-broadcast.index');
      urlStr += '&store_id=' + id;
      wx.request({
        url: urlStr,
        data: {},
        header: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        },
        success: function(res) {
          if (res.data.result == 1) {
            that.setData({
              vedioSrc: res.data.data.url,
            });
            console.log(res.data.data.url);
            if (that.data.vedioSrc) {
              that.audioCtx = wx.createAudioContext('yp');
              that.audioCtx.play();
            }
          }
        },
        fail: function(res) {
        },
        complete: function(res) {
        }
      });
    }, 5000);
  },
  closeTimeInterval() {
    clearInterval(intervalid);
  },
  getHotelData() {
    var that = this;
    let urlStr = app.getNetAddresss('plugin.hotel.frontend.cashier.qr-code.index');
    app._getNetWork({
      url: urlStr,
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            qrcode: res.data.url
          });
        }
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },
  saveShareImg(){
      let imgSrc = this.data.qrcode;
      wx.downloadFile({
        url: imgSrc,
        success: function (res) {
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: (data) => {
              wx.showToast({
                title: '保存成功',
                icon: 'none',
                duration: 2000
              })
            },
            fail: function (err) {
              console.log(err);
              if (err.errMsg === 'saveImageToPhotosAlbum:fail auth deny') {
                console.log('当初用户拒绝，再次发起授权');
                wx.openSetting({
                  success(settingdata) {
                    if (settingdata.authSetting['scope.writePhotosAlbum']) {
                      wx.showToast({
                        icon: 'none',
                        title: '获取权限成功,再次长按保存图片',
                        duration: 1500
                      });
                    } else {
                      wx.showToast({
                        icon: 'none',
                        title: '获取权限失败,保存图片需要用户授权',
                        duration: 1500
                      });
                    }
                  }
                });
              }
            }
          })
        },
        fail: (err) => {
          wx.saveImageToPhotosAlbum({
            filePath: imgSrc,
            success: (data) => {
              wx.showToast({
                title: '保存成功',
                icon: 'none',
                duration: 2000
              })
            },
            fail: function (err) {
              console.log(err);
            }
          })
        }
      })
  },
  getShortLink(e){
    let mid = wx.getStorageSync("yz_uid");
    let plu = e.currentTarget.dataset.plu;
    let json = {};
    let api = 'plugin.wechat-short-link.frontend.index.get-url'
    if (plu == 'privatechain') {
      api = 'plugin.private-chain.frontend.index.index';
      json = {
        path: `packageC/o2o/HomeSeller/HomeSeller`,
        params: `store_id=${this.options.store_id||this.data.store_id}&mid=${mid}`,
        share_type: 'store',
        id: this.options.store_id||this.data.store_id
      }
    }
    app._postNetWork({
      url: app.getNetAddresss(api),
      data: json,
      success:res => {
        console.log(res)
        if(res.data.result == 1){
          this.setData({
            videoLinkUrl: res.data.data.url||false,
            videoLinkText: res.data.data.text,
            videoLinkDesc: res.data.data.desc,
            showShortLink: true,
            showSahre: false
          });
        }else{
          app.tips(res.data.msg)
        }
      }
    })
  },
  onCopyShortLink(e){
    let type = e.currentTarget.dataset.type;
    this.onClipboardData(this.data[type]);
  },
  onClipboardData(data){
    wx.setClipboardData({
      data: data,
      success(res) {
        wx.showToast({
          icon: 'none',
          title: '复制成功',
          duration: 1000
        });
      },fail(err){
        console.log(err);
      }
    });
  },
  clonePop(e){
    let { tag, status } = e.target.dataset;
    this.setData({
      [tag]: status
    })
  }
});
